package com.smzd.framework.core.actions;

import java.util.Map;

import org.springframework.validation.BindingResult;

import com.smzd.core.domain.IScopedEntity;
import com.smzd.core.domain.IntIdEntity;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.db.SRPage;

public abstract class AbstractScopedController<E extends IScopedEntity<S>, S extends IntIdEntity> extends
        AbstractController<E> {

    public String toAddPage(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initScope(scopeId, elem);
        return toAddPage(model, elem, result);
    }

    public String postAddData(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initScope(scopeId, elem);
        return postAddData(model, elem, result);
    }

    public String toListPage(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initScope(scopeId, elem);
        return toListPage(model, elem, result);
    }

    public String getListData(Map<String, Object> model, int scopeId, SRPage<S, E> page, BindingResult result)
            throws Exception {
        if (scopeId == 0) {// 上不存在，或者不知道owner.id，则不给出任何数据
            return JsonHelper.getFailJsonString("ownerId为0的列表数据为空");
        }
        if (page.getScope() == null || page.getScope().getId() == null) {
            S scope = getScope(scopeId);
            page.setScope(scope);
        }
        return getListData(model, page, result);
    }

    public String toEditPage(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initScope(scopeId, elem);
        return toEditPage(model, elem, result);
    }

    public String postEditData(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initScope(scopeId, elem);
        return postEditData(model, elem, result);
    }

    public String postRemoveData(Map<String, Object> model, int scopeId, E elem, BindingResult result) throws Exception {
        initScope(scopeId, elem);
        return postRemoveData(model, elem, result);
    }

    protected abstract S getScope(int scopeId);

    protected void initScope(int scopeId, E elem) {
        if (elem.getScope() == null || elem.getId() == null) {
            S scope = scopeId == 0 ? null : getScope(scopeId);
            elem.setScope(scope);
        }
    }
}
